package com.yogee.topseller.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpActivity1;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.view.impl.GuideLoginRegist;
import com.yogee.topseller.activity.login.view.impl.RegisterLabelActivity;
import com.yogee.topseller.bean.HuiyuanListModel;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.ImmersedStatusbarUtils;
import com.yogee.topseller.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.R.attr.path;

public class SplashActivity extends HttpActivity1 {
    private CountDownTimer timer;
    private boolean flag = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MobclickAgent.setDebugMode(true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_launch;
    }

    @Override
    protected void initView() {
//        MainActivity.initSystemBar(this);
//        ImmersedStatusbarUtils.initAfterSetContentView(this,findViewById(R.id.img_splash));
        Intent itnIn = getIntent();
        String action=getIntent().getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
//            String url = itnIn.getDataString();
//            String filePath = getRealPathFromURI(SplashActivity.this, Uri.parse(url));
//            LogUtils.e("kaishi", "path:" + path);
//            try {
//                InputStream in = this.getContentResolver().openInputStream(Uri.parse(url));//io
//                FileOutputStream out = new FileOutputStream(new File(filePath));//文件输出到开发app路径
//                byte[] b = new byte[1024];
//                try {
//                    while ((in.read(b)) != -1) {
//                        out.write(b);
//                    }
//                    in.close();
//                    out.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
        }
        timer = new CountDownTimer(2000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                LogUtils.e("times","启动"+millisUntilFinished+"");
            }

            @Override
            public void onFinish() {
                LogUtils.e("times","结束了");
                if(!subscriber.isUnsubscribed()){
                    subscriber.unsubscribe();
                }
                if(!flag){
                    startActivity(new Intent(SplashActivity.this, GuideLoginRegist.class));

                }else{
                    startActivity(new Intent(SplashActivity.this, MainActivity1.class));
                }
                overridePendingTransition(0, android.R.anim.fade_out);
                finish();
            }
        };
        finishActivity1();




    }

    /**
     * 通过Uri获取文件在本地存储的真实路径
     * @param act
     * @param contentUri
     * @return
     */
    private static String getRealPathFromURI(Activity act, Uri contentUri) {

        // can post image
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = act.managedQuery(contentUri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        if (cursor==null) {
            String path = contentUri.getPath();
            return path;
        }

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);

    }

    private void finishActivity(){
        Observable.timer(2000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {

                        // 第一次打开app
                        if ((Boolean) SharedPreferencesUtils.get(SplashActivity.this, SharedPreferencesUtils.FIRST_TIME, true)) {
//                            startActivity(new Intent(SplashActivity.this, FirstStartActivity.class));
                            MobclickAgent.onEvent(SplashActivity.this, "start_App");
                            SharedPreferencesUtils.put(SplashActivity.this,SharedPreferencesUtils.FIRST_TIME,false);
                        }
                        if(AppUtil.isExamine(SplashActivity.this)) {
                            startActivity(new Intent(SplashActivity.this, MainActivity1.class));
                            overridePendingTransition(0, android.R.anim.fade_out);
                            finish();
                        }else {
                            searchFilter();
                        }

//                        if(AppUtil.isExamine(SplashActivity.this)){
//                            startActivity(new Intent(SplashActivity.this, MainActivity1.class));
//                        }else{
//                            startActivity(new Intent(SplashActivity.this, GuideLoginRegist.class));
//                        }
//


                    }
                });
    }


    private void finishActivity1(){
        timer.start();
        if ((Boolean) SharedPreferencesUtils.get(SplashActivity.this, SharedPreferencesUtils.FIRST_TIME, true)) {
//                            startActivity(new Intent(SplashActivity.this, FirstStartActivity.class));
            MobclickAgent.onEvent(SplashActivity.this, "start_App");
            SharedPreferencesUtils.put(SplashActivity.this,SharedPreferencesUtils.FIRST_TIME,false);
        }
        if(AppUtil.isExamine(SplashActivity.this)) {
            flag = true;
        }else {
            setLabels();
        }
    }

    private void searchFilter() {
        HttpManager.getInstance().islogOut().compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(o.getIslog().equals("0")){
                    startActivity(new Intent(SplashActivity.this, GuideLoginRegist.class));
                }else{
                    startActivity(new Intent(SplashActivity.this, MainActivity1.class));
                }
                overridePendingTransition(0, android.R.anim.fade_out);
                finish();
            }
        }, this));
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("启动页"); //手动统计页面("SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("启动页"); //手动统计页面("SplashScreen"为页面名称，可自定义)，必须保证 onPageEnd 在 onPause 之前调用，因为SDK会在 onPause 中保存onPageEnd统计到的页面数据。
        MobclickAgent.onPause(this);
    }

    @Override
    public void showMsg(String msg) {
//        super.showMsg(msg);
        flag = false;
//        startActivity(new Intent(SplashActivity.this, GuideLoginRegist.class));
//        overridePendingTransition(0, android.R.anim.fade_out);
//        finish();
    }

    BaseSubscriber subscriber = new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
        @Override
        public void onNext(ResultBean o) {
            if(o.getIslog().equals("0")){
                flag = false;

            }else{
                flag = true;
            }
        }
    }, this);
    private void setLabels(){
        HttpManager.getInstance().islogOut().compose(this.bindRecycler()).subscribe(subscriber);
    }
    Call call;
    private void setlabels1() {
        if (!NetUtil.isNetworkAvailable()) {
//            ToastUtils.showToast(SplashActivity.this, "网络中断了，请重新链接网络。");
            startActivity(new Intent(SplashActivity.this, GuideLoginRegist.class));
            overridePendingTransition(0, android.R.anim.fade_out);
            finish();
        }else{
            //网络调取api
//        OkHttpClient okHttpClient = new OkHttpClient();

            OkHttpClient okHttpClient =
                    new OkHttpClient.Builder()
                            .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                            .writeTimeout(20,TimeUnit.SECONDS)//设置写的超时时间
                            .connectTimeout(20,TimeUnit.SECONDS)//设置连接超时时间
                            .build();
            Request.Builder builder = new Request.Builder();
            RequestBody requestBody = RequestBody
                    .create(MediaType.parse("text/plain;chaset=utf-8"),"");
            Request request = builder.post(requestBody)
                    .url(Config.BASE_URL+"islogOut")
//                .addHeader("Authorization", "APPCODE " + appCode)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();
            call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                        //失败处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }
//                        ToastUtils.showToast(SplashActivity.this, "保存失败");
                            flag = false;
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                        //成功处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }

                            //组装json来回显银行卡号
                            try {
                                Gson gson = new Gson();
                                String result = response.body().string().replace("\n","");
                                LogUtils.e("success",result);
                                JSONObject jsonObject = new JSONObject(result);
                                ResultBean o = gson.fromJson(jsonObject.getString("data"),ResultBean.class);
                                if(o.getIslog().equals("0")){
                                    flag = false;

                                }else{
                                    flag = true;

                                }

                            } catch (Exception e) {
                               flag = false;
                            }
                        }
                    });
                }
            });
        }



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }
}
